<template>
  <div class="search">
    <van-nav-bar fixed title="商品列表" left-arrow @click-left="$router.go(-1)" />

    <van-search
      readonly
      shape="round"
      background="#ffffff"
      :value="searchKey || '请输入搜索关键词'"
      show-action
      @click="$router.push('/search')"
    >
      <template #action>
        <van-icon class="tool" name="apps-o" />
      </template>
    </van-search>

    <!-- 排序选项按钮 -->
    <div class="sort-btns">
      <div class="sort-item" v-for="(item) in tabTitles" :key="item.id" :style="{color: activeIndex === item.id ? '#ee0a24' : '#000'}" @click="onTabClick(item)">{{ item.title }}</div>
    </div>

    <div class="goods-list">
      <GoodsItem v-for="item in proList" :key="item.goods_id" :item="item"></GoodsItem>
    </div>
  </div>
</template>

<script>
import { getProList } from '@/api/product'
import GoodsItem from '@/components/GoodsItem.vue'
export default {
  name: 'SearchIndex',
  components: {
    GoodsItem
  },
  data () {
    return {
      page: 1,
      proList: [],
      activeIndex: 1,
      tabTitles: [
        { id: 1, title: '综合', sortType: 'all' },
        { id: 2, title: '销量', sortType: 'sales' },
        { id: 3, title: '价格', sortType: 'price' }
      ]
    }
  },
  computed: {
    // 获取地址栏传来的搜索关键字
    searchKey () {
      return this.$route.query.search
    }
  },
  async created () {
    const { data: { list } } = await getProList({ categoryId: this.$route.query.categoryId, goodsName: this.searchKey, page: this.page })
    this.proList = list.data
  },
  methods: {
    async onTabClick (item) {
      this.activeIndex = item.id
      const { data: { list } } = await getProList({ sortType: item.sortType, goodsName: this.searchKey, page: this.page })
      this.proList = list.data
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  padding-top: 46px;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .tool {
    font-size: 24px;
    height: 40px;
    line-height: 40px;
  }

  .sort-btns {
    display: flex;
    height: 36px;
    line-height: 36px;
    .sort-item {
      text-align: center;
      flex: 1;
      font-size: 16px;
    }
  }
}

// 商品样式
.goods-list {
  background-color: #f6f6f6;
}
</style>
